package com.johnny.xia.util.google;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.johnny.xia.util.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : Ga4
 * @Description : ga4 的服务端上报代码测试
 * @Author : Xia Long
 * @MailTo : johnny.xia@qq.com
 * @Date: 2024/04/16 15:00
 */
@Slf4j
public class Ga4 {

    private static final String GA_URL = "https://www.google-analytics.com";
//    //Moncler uat 后台
    private static final String GA_MEASUREMENT_ID = "G-MTDXSPX2ND";
    private static final String GA_API_SECRET = "ypzOco0kQEugo8NVeO6NZQ";


//    private static final String GA_MEASUREMENT_ID = "G-Z1W9QE10F0";
//    private static final String GA_API_SECRET = "_5TCfhCDSZaQc9oPR56abA";

//xialong 的 ga 后台
//    private static final String GA_MEASUREMENT_ID = "G-GS4PRLBPEQ";
//    private static final String GA_API_SECRET = "Wx9Os17VR-6doX1Q4g7JYw";

    private String cid = ""; // 客户端传过来，由 ga 对象中获取。

    public static void main(String[] args) throws InterruptedException {
/*        for(int i=0;i<1;i++){
            JSONObject json = buildOrder();
            try {
                String gaurl =  GA_URL + "/mp/collect?measurement_id=" + GA_MEASUREMENT_ID + "&api_secret=" + GA_API_SECRET;
                int rescode = sendCollect(gaurl,json);
                String gaDebugUrl =  GA_URL + "/debug/mp/collect?measurement_id=" + GA_MEASUREMENT_ID + "&api_secret=" + GA_API_SECRET;
                sendCollect(gaDebugUrl,json);
//                System.out.println("resCode:"+rescode);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Thread.sleep(3000);
        }*/

        try{

            JSONObject json = strToJson();

            String gaurl =  GA_URL + "/mp/collect?measurement_id=" + GA_MEASUREMENT_ID + "&api_secret=" + GA_API_SECRET;
            sendCollect(gaurl,json);

            String gaDebugUrl =  GA_URL + "/debug/mp/collect?measurement_id=" + GA_MEASUREMENT_ID + "&api_secret=" + GA_API_SECRET;
            sendCollect(gaDebugUrl,json);
        }catch (Exception e){
            e.printStackTrace();
        }


    }


    public static JSONObject buildOrder() {
        JSONObject postData = new JSONObject();

        JSONArray events = new JSONArray();
        JSONObject event = new JSONObject();

        JSONObject params = new JSONObject();


        Date date = new Date();
        String localDay = DateUtil.date2Str(date,"yyyyMMdd");
        String localHour = DateUtil.date2Str(date,"HH:mm");

        //订单头信息
        params.put("transaction_id", DateUtil.date2Str(date,"yyyyMMddHHmmssSSS"));
        params.put("value", 14350.00); //金额
        params.put("tax", 0.00);
        params.put("shipping", 0.00);
        params.put("currency", "CNY");
        params.put("nav_country_code","CN");
        params.put("region","CHINA");
        params.put("navigationCurrency","CNY");
        params.put("environment","DEVELOPMENT_SYSTEM");
        params.put("local_day",localDay);
        params.put("local_hour",localHour);
        params.put("full_url","https://www.moncler.cn/order-confirmation?order="+DateUtil.date2Str(date,"yyyyMMddHHmmssSSS"));
        params.put("page_title","order-confirmation");
        params.put("isWebview",false);
        params.put("page_category","thank-you");
        params.put("page_language","cn");
        params.put("pageMacrocategory","checkout");
        params.put("page_status",200);
        params.put("visitorID","");

//        Map<String,Object> upMap = new HashMap<>();
//        upMap.put("system","website");
//        params.put("ep",epMap);
//        params.put("up",epMap);

        //绑定c端用户信息
        /**
         * 由c 端获取 ga 对象数据，然后放到 订单的扩展里面，cid 一定要有，而且需要通过c端ga 对象真实获取，不然导致订单挂不上渠道
         * {
         * "dl": "https://www.gucci.cn/zh/transaction/new/check",
         * "sd": "24-bit",
         * "sr": "393x852",
         * "vp": "393x659",
         * "cid": "2041709535.1713244936",
         * "gid": "879581584.1713244936",
         * "gtm": "457e44f0za200"
         * }
         *
         */

        String clientId = "1165871181.1711014921";
        params.put("cid",clientId);
        params.put("client_id",clientId);
        params.put("session_id","1713316269");
        //行信息
        params.put("items", buildOrderLines());
        event.put("name", "purchase");
        event.put("params", params);
        events.add(event);
        postData.put("client_id", clientId);

//        JSONArray user_properties = new JSONArray();
//        JSONObject up = new JSONObject();
//        up.put("system","website");
//        user_properties.add(up);

        postData.put("user_properties",builderUserProperties());
        postData.put("events", events);
        return postData;
    }


    private static JSONObject strToJson(){
        String jsonStr = "{\n" +
                "\"events\": [\n" +
                "{\n" +
                "\"name\": \"purchase\",\n" +
                "\"params\": {\n" +
                "\"cid\": \"162611797.1713516757\",\n" +
                "\"tax\": \"0.00\",\n" +
                "\"items\": [\n" +
                "{\n" +
                "\"index\": 0,\n" +
                "\"price\": 20900,\n" +
                "\"item_id\": \"I20931C0004968950\",\n" +
                "\"currency\": \"cny\",\n" +
                "\"quantity\": \"1\",\n" +
                "\"item_name\": \"Parnaiba Long Down Jacket\",\n" +
                "\"item_brand\": \"Moncler\",\n" +
                "\"item_variant\": \"999\",\n" +
                "\"item_category\": \"OUTERWEAR\",\n" +
                "\"item_category2\": \"instock\",\n" +
                "\"item_category3\": \"LONG COAT/CAR COAT\",\n" +
                "\"item_category4\": \"093\",\n" +
                "\"item_category5\": \"no\"\n" +
                "}\n" +
                "],\n" +
                "\"value\": 20900,\n" +
                "\"region\": \"CHINA\",\n" +
                "\"system\": \"website\",\n" +
                "\"currency\": \"CNY\",\n" +
                "\"full_url\": \"https://www.moncler.cn/order-confirmation?orderNo=1782248062570505&payresult=1\",\n" +
                "\"shipping\": \"0.00\",\n" +
                "\"client_id\": \"162611797.1713516757\",\n" +
                "\"isWebview\": false,\n" +
                "\"local_day\": \"20240422\",\n" +
                "\"page_path\": \"/order-confirmation\",\n" +
                "\"visitorID\": \"4A63E8EC-7EDB-EE11-9078-0017FA03978E\",\n" +
                "\"local_hour\": \"11:28\",\n" +
                "\"page_title\": \"order-confirmation\",\n" +
                "\"session_id\": \"1713516757\",\n" +
                "\"environment\": \"DEVELOPMENT_SYSTEM\",\n" +
                "\"page_status\": 200,\n" +
                "\"page_category\": \"thank-you\",\n" +
                "\"page_language\": \"cn\",\n" +
                "\"transaction_id\": \"1782309626073095\",\n" +
                "\"nav_country_code\": \"CN\",\n" +
                "\"user_login_state\": \"true\",\n" +
                "\"pageMacrocategory\": \"checkout\",\n" +
                "\"navigationCurrency\": \"CNY\"\n" +
                "}\n" +
                "}\n" +
                "],\n" +
                "\"client_id\": \"162611797.1713516757\",\n" +
                "\"user_properties\": {\n" +
                "\"system\": {\n" +
                "\"value\": \"website\"\n" +
                "}\n" +
                "}\n" +
                "}";

        return JSONObject.parseObject(jsonStr);
    }

    private static Map<String,Object> builderUserProperties() {

        Map<String,Object> userProMap = new HashMap<>();
        Map<String,Object> valueMap = new HashMap<>();
        valueMap.put("value","website");
        userProMap.put("system",valueMap);
        return userProMap;
    }

    /**
     * {
     *   "client_id": "CLIENT_ID",
     *   "user_properties": {
     *     "system": {
     *       "value": "website" // 根据实际情况选择 "website" 或 "app"
     *     }
     *   },
     *   "events": [{
     *     "name": "interaction",
     *     "params": {}
     *   }]
     * }
     * @return
     */

    public static JSONArray buildOrderLines() {
        JSONArray items = new JSONArray();
        int index = 0;
        JSONObject item = new JSONObject();
        item.put("item_id", "62748dcfaefd6c00014b288b");
        item.put("item_name", "Moncler Maya 冬季短款男士羽绒服夹克外套");
        item.put("index", index);
        item.put("item_brand", "Moncler");
        item.put("price", 14350.00);
        item.put("quantity",1);
        items.add(item);
        return items;
    }


    private static int sendCollect(String urlStr,JSONObject postData) throws Exception {
        byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);


        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.getOutputStream().write(postDataBytes);

        int responseCode = connection.getResponseCode();

        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println("urlStr:"+urlStr);
        System.out.println(responseCode+":"+postData.toJSONString());
        System.out.println("response:"+response.toString());
//        System.out.println("resCode"+responseCode);


        connection.disconnect();
        return responseCode;
    }
}
